/**
 * Created by tdzl2003 on 8/24/16.
 */
import React from 'react';
import { Popconfirm, Button } from 'antd';
import {get, $delete, put} from '../../logics/rpc';
import ObjectTable from '../../components/ObjectTable';
import alert from '../../utils/alert';
import SetPwdModal from './SetPwdModal';
import AddAccModal from './AddAccModal';
import md5 from '../../logics/md5';

export default class List extends React.Component{
  state={
    setPwdModalVisible: false,
    addAccModalVisible: false,
  };
  fetchData = (params) => get('/admin/user/list', params);
  columns = [{
    title: 'ID',
    dataIndex: 'id',
    width: 60,
  },  {
    title: '账号名',
    dataIndex: 'user_login',
  }, {
    title: '',
    render: acc => (
      <div>
        <Popconfirm placement="topRight" title={`确认删除账号${acc.name}吗？`} onConfirm={()=>this.deleteAcc(acc)}>
          <Button size="small">删除</Button>
        </Popconfirm>
        <Button size="small" onClick={()=>this.setPwd(acc)}>修改密码</Button>
      </div>
    ),
  }];

  async deleteAcc(acc) {
    try {
      await $delete(`/admin/user/${acc.id}`);
      this.refs.table.removeItem(acc);
    } catch (err) {
      switch (err.code) {
        case 409: alert('您不能删除您自己！');break;
        default:alert('删除失败');break;
      }
    }
  }
  setPwd(acc) {
    this.setState({
      setPwdModalVisible: true,
      acc: acc,
    });
  }
  dismissSetPwd = () => {
    this.setState({
      setPwdModalVisible: false,
    })
  }
  onSubmitSetPwd = async ({newPwd}) => {
    const {acc} = this.state;
    try {
      await put(`/admin/user/${acc.id}/pwd`, {
        newPwd: md5(newPwd),
      });
      alert('修改成功');
    } catch (err) {
      alert('修改失败');
    }
  };
  showAddAcc = () =>{
    this.setState({
      addAccModalVisible: true,
    });
  };
  dismissAddAcc = () => {
    this.setState({
      addAccModalVisible: false,
    });
  }
  renderHeader = () => {
    return (
      <div>
        <Button onClick={this.showAddAcc}>添加管理员账号</Button>
      </div>
    );
  };
  onAccAdded = () => {
    this.refs.table.refresh();
  };
  render() {
    const {setPwdModalVisible, addAccModalVisible} = this.state;

    return (
      <div>
        <ObjectTable
          columns={this.columns}
          fetchData={this.fetchData}
          ref="table"
          title={this.renderHeader}
        />
        <SetPwdModal
          visible={setPwdModalVisible}
          dismiss={this.dismissSetPwd}
          onSubmit={this.onSubmitSetPwd}
        />
        <AddAccModal
          visible={addAccModalVisible}
          dismiss={this.dismissAddAcc}
          onAdded={this.onAccAdded}
        />
      </div>
    );
  }
}
